package com.wq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wq.common.R;
import com.wq.entity.Category;
import com.wq.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ description
 * @ author wuyunpeng
 * @ create 2022-07-21 13:48
 */
@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加成功!");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        categoryService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    @DeleteMapping
    public R<String> delete(Long id) {
        categoryService.remove(id);
        return R.success("分类删除成功!");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("修改后的分类为,{}", category);
        categoryService.updateById(category);
        return R.success("修改分类成功!");
    }

    @GetMapping("/list")
    public R<List> list(Category category) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(!StringUtils.isEmpty(category.getType()), Category::getType, category.getType());
        lqw.orderByAsc(Category::getType).orderByDesc(Category::getSort).orderByDesc(Category::getUpdateTime);
        final List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
}
